package com.ctsi.security.app.controller;

import com.ctsi.commons.util.StringUtil;
import com.ctsi.commons.util.UtilMisc;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.framework.security.util.SecurityUtil;
import com.ctsi.organise.common.api.PersonServiceProxy;
import com.ctsi.organise.common.api.UserLoginServiceProxy;
import com.ctsi.organise.common.model.Organise;
import com.ctsi.security.*;
import com.ctsi.security.app.vo.RoleDataObjectAddVO;
import com.ctsi.security.app.vo.RolePermissionAddVO;
import com.ctsi.security.domain.*;
import com.ctsi.security.service.DataObjectTypeService;
import com.ctsi.security.service.RoleSecurityService;
import com.ctsi.system.api.IDictionaryData;
import com.ctsi.system.service.api.DictionaryServiceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class SRoleController {
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SRoleController.class);
    String dataObjectTypePerm = "sysModule";
    String action = "SELECT";
    @Autowired
    private PermissionRole roleService;
    @Autowired
    private PartySrole secSRoleService;
    @Autowired
    private RoleSecurityService roleSecurityService;
    @Autowired
    private DataObjectTypeService dataObjectTypeService;
    private PermissionSer permissionService;
    private String dictType = "system_module";
    private String dateObjectType = "organChain";
    @Autowired
    private PermissionTypeSer permissionTypeService;
    private Map<String, String> configRoleType = new HashMap<>();// key为roleType,value为 roleType在字典中对应的值
    @Autowired
    private PersonServiceProxy personServiceProxy;
    private UserLoginServiceProxy userLoginServiceProxy;
    @Autowired
    private ISecurity iSecurity;
	@Autowired
    private DictionaryServiceProxy dic;// 数据字典类

    public ModelAndView selectpermision(HttpServletRequest request, HttpServletResponse response) {
        request.setAttribute("hasall", !iSecurity.isControl(SecurityUtil.getUser().getLoginId(), dataObjectTypePerm, action));
        return new ModelAndView("security/role/selectpermision");
    }

//    /**
//     * 功能权限 layer弹窗
//     *
//     * @param request
//     * @param response
//     * @return
//     */
//    public ModelAndView selectpermisionLayer(HttpServletRequest request, HttpServletResponse response) {
//        request.setAttribute("hasall", !iSecurity.isControl(SecurityUtil.getUser().getLoginId(), dataObjectTypePerm, action));
//        return new ModelAndView("security/role/selectpermisionLayer");
//    }

    /**
     * 角色列表
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value = "/security/roles")
    public ModelAndView viewRole(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndView("role");
    }

    /**
     * 添加角色
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value = "/security/roles-add")
	public ModelAndView addRole(HttpServletRequest request, HttpServletResponse response) {
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		int i = 0;
		for (Map.Entry<String, String> entry : configRoleType.entrySet()) {
			if (i > 0) {
				sb.append(",");
			}
			sb.append("['").append(entry.getKey()).append("'");
			sb.append(",'").append(entry.getValue()).append("'");
			sb.append("]");
			i++;
		}
		sb.append("]");
		request.setAttribute("configRoleType", sb.toString());
		return new ModelAndView("addRole");
	}

	// 打开添加修改角色信息  1
    @GetMapping(value="/security/role-edit/{roleId}")
	public UnifiedResponse<SRole> editRole(@PathVariable("roleId") String roleId) {
		SRole sRole;
		if (!roleId.equals("")) {
			sRole = roleService.findSRoleById(roleId);
			Assert.notNull(sRole);
		} else {
			sRole = new SRole();
		}
		if (UtilValidate.isNotEmpty(sRole.getParentRoleId())) {
			SRole sRoleParent = roleService.findSRoleById(sRole.getParentRoleId());
		}
		return UnifiedResponse.ok(sRole);
	}
//
//
	// 保存角色
//    @PostMapping(value="/security/saverole")
//	public ModelAndView saveRole(HttpServletRequest request, HttpServletResponse response) {
//		// 返回Index
//		return this.saveOrUpdateRole(request, response);
//	}
//
//	// 更新角色
//	public ModelAndView updateRole(HttpServletRequest request, HttpServletResponse response) {
//		logger.debug("当前登录用户{}更新角色对应的功能ID是{}", SecurityUtil.getUser().getLoginId(), getPermissionId("updateRole"));
//		return this.saveOrUpdateRole(request, response);
//	}
//

    /**
     * 保存角色信息  1
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value="/security/saverole")
	public UnifiedResponse<Void> saveOrUpdateRole(HttpServletRequest request, HttpServletResponse response) {
		String roleId = request.getParameter("roleId");
		String roleName = request.getParameter("roleName");
		String roleType = request.getParameter("roleType");
		String dataObject = request.getParameter("dataObject");
		String description = request.getParameter("description");
		String parentRoleId = request.getParameter("parentRoleId");
		String moduleType = request.getParameter("moduleType");
		String storNum = request.getParameter("paixu");
		String businessId = request.getParameter("businessId");
		String organId = request.getParameter("parentId");
		String organName = request.getParameter("parentName");

		organId = organId == null ? "" : organId.trim();
		organName = organName == null ? "" : organName.trim();
		roleId = roleId == null ? "" : roleId.trim();
		roleName = roleName == null ? "" : roleName.trim();
		description = description == null ? "" : description.trim();
		dataObject = dataObject == null ? "" : dataObject.trim();
		parentRoleId = parentRoleId == null ? "" : parentRoleId.trim();
		moduleType = moduleType == null ? "" : moduleType.trim();
		businessId = businessId == null ? "" : businessId.trim();
		roleType = roleType == null ? "" : roleType.trim();
		if (UtilValidate.isEmpty(storNum)) {
			storNum = String.valueOf(System.currentTimeMillis());
		}
		SRole sRole = new SRole();
		sRole.setRoleId(roleId);
		sRole.setRoleName(roleName);
		sRole.setDataObject(dataObject);
		sRole.setDescription(description);
		sRole.setParentRoleId(parentRoleId);
		sRole.setModuleType(moduleType);
		sRole.setSortNum(Long.parseLong(storNum));
		sRole.setBusinessId(businessId);
		sRole.setOrganiseId(organId);
		sRole.setOrganiseName(organName);
		sRole.setRoleType(roleType);
		if (UtilValidate.isEmpty(roleId)) {
			if (roleService.valRoleName(roleName)) {
                return UnifiedResponse.error("-1", "数据库中已存在该名称");
			} else {
				// roleService.addRole(sRole);
				String loginIds = request.getParameter("memberId");
				String loginNames = request.getParameter("member");
				String partyIds = request.getParameter("partyId");
				roleService.addSRoleMem(sRole, loginIds, loginNames, partyIds, null, null, null, null);
			}
		} else {
			roleService.updRole(sRole);
		}
        request.setAttribute("EVENT_MSG", "保存成功");
		return UnifiedResponse.ok();
	}
//
    /**
     * 查询角色数据 1
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/security/roles-query")
	public UnifiedResponse<Page> roleDataPage(HttpServletRequest request, HttpServletResponse response) {
		int skipResults = 0;
		int pageSize = Page.DEFAULT_PAGE_SIZE;
		String start = request.getParameter("start");
		String limit = request.getParameter("pageSize");
		if (UtilValidate.isNotEmpty(limit)) {
			pageSize = Integer.parseInt(limit);
		}
		if (UtilValidate.isNotEmpty(start))
			skipResults = Integer.parseInt(start);
		// 当前登录用户
		String userLogin = SecurityUtil.getUser().getLoginId();
		// 增加查询功能
		String roleName = request.getParameter("roleName");
		if (UtilValidate.isNotEmpty(roleName)) {
			roleName = roleName.trim();
		} else {
			roleName = null;
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("roleName", roleName);
		String moduleType = request.getParameter("moduleType");
		if (UtilValidate.isNotEmpty(moduleType)) {
			params.put("moduleType", moduleType);
		}

		String businessId = request.getParameter("businessId");
		if (UtilValidate.isNotEmpty(businessId)) {
			params.put("businessId", businessId);
		}

		String module = request.getParameter("module");
		if (UtilValidate.isNotEmpty(module)) {
			if (module.startsWith("%")) {
				module = module.substring(1);
			}
			if (module.endsWith("%")) {
				module = module.substring(0, module.length() - 1);
			}
		}
		Page page = secSRoleService.queryRole(userLogin, "sysModule", "SELECT", pageSize, skipResults, params);
		return UnifiedResponse.ok(page);
	}
//
//
	// 删除角色信息  1
    @DeleteMapping(value = "/security/delete-role")
	public UnifiedResponse<Void> delRole(HttpServletRequest request, HttpServletResponse response) {
		String roleIds = request.getParameter("roleIds");
		if (UtilValidate.isEmpty(roleIds)) {
            return UnifiedResponse.ok();
        }
		try {
			roleService.remRole(StringUtil.split(roleIds, ","));
			return UnifiedResponse.ok();
		} catch (DelRoleException exception) {
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append("{\"success\":false,\"list\":\"");
			stringBuilder.append(exception.getMessage());
			stringBuilder.append("\"}");
			logger.error(stringBuilder.toString());
		}
		return UnifiedResponse.error("-1", "删除失败!");
	}
//
//	// 显示角色下的人员列表
//	public ModelAndView viewRoleUser(HttpServletRequest request, HttpServletResponse response) {
//		String roleId = request.getParameter("roleId");
//		roleId = roleId == null ? "" : roleId.trim();
//		String roleName = request.getParameter("roleName");
//		// 判断是否提交roleName参数，如果没有提交，则由角色Id找到相应的RoleName
//		if (UtilValidate.isEmpty(roleName)) {// 为空，如果roleId不空，由roleId查找相应的roleName
//			if (!roleId.equals("")) {
//				SRole srole = roleService.findSRoleById(roleId);
//				if (srole != null) {// 找到相应的权限角色
//					roleName = srole.getRoleName();
//				} else {// 没有找到相应的权限角色
//					logger.warn("There is not correspond roleName to {}", roleId);
//				}
//			} else {// roleId为空
//				roleName = "";
//			}
//		}
//		logger.info("The roleId is {},The roleName is {}", roleId, roleName);
//		request.setAttribute("roleId", roleId);
//		request.setAttribute("roleName", roleName);
//		String returnUrl = request.getParameter("returnUrl");
//		if (UtilValidate.isNotEmpty(returnUrl)) {
//			return new ModelAndView(returnUrl);
//		}
//		return new ModelAndView("security/role/roleUser");
//	}
//

	/**
	 * 查询角色下的用户 1
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping(value = "/srole/members")
	public UnifiedResponse<Page<Map<String,Object>>> roleUserDataPage(HttpServletRequest request, HttpServletResponse response) {
		String roleId = request.getParameter("roleId");
		String userLoginId = request.getParameter("userLoginId");
		String userLoginName = request.getParameter("userLoginName");
		int skipResults = 0;
		int pageSize = Page.DEFAULT_PAGE_SIZE;
		String start = request.getParameter("start");
		String limit = request.getParameter("pageSize");
		if (UtilValidate.isNotEmpty(limit)) {
			pageSize = Integer.parseInt(limit);
		}
		if (UtilValidate.isNotEmpty(start)){
            skipResults = Integer.parseInt(start);
        }
		Page page = roleService.queryRoleUser(pageSize, skipResults, roleId, userLoginId, userLoginName,SecurityUtil.getUser().getLoginId());
		SRole srole = roleService.findSRoleById(roleId);
		List<SRoleUser> listResult = page.getResult();
		List<Map<String, Object>> listresult = new ArrayList<>();
		// 处理数据（根据类型查询）
		for (SRoleUser user : listResult) {
			String orgnamestr = "";
			if (user.getType().equals(SRoleUser.typeUser)) {
				String partyid = user.getPartyId();
				List<Organise> organs = (List<Organise>) personServiceProxy.getPesonAsc(partyid);
				List<String> organNames = organs.stream().map(organise -> organise.getPartyName()).collect(Collectors.toList());
                orgnamestr = StringUtil.join(organNames, "> ");
			}
			Map<String, Object> result = UtilMisc.toMap(user);
			result.put("organ", orgnamestr);
			listresult.add(result);
		}
		//long start, long totalSize, int pageSize, List<E> data
		return UnifiedResponse.ok(new Page(skipResults,page.getTotalCount(),pageSize,listresult));
	}
//
//	/**
//	 * 组织层级的排序顺序为：自组织，父组织；遍历获得组织时注意顺序
//	 *
//	 * @param organ
//	 * @param organises
//	 */
//	private void getOrgAsc(Organise organ, List<Organise> organises) {
//		if (organ == null) {
//			logger.warn("organ 为空！！");
//		} else {
//			organises.add(organ);
//			if (organ.getParentId() != null) {
//				Organise organise = OrganiseFactoryBean.getInstance().getOrganiseProxy().findOrganiseById(organ.getParentId());
//				this.getOrgAsc(organise, organises);
//			}
//		}
//
//	}
//
//	/**
//	 * 检查功能权限是否能添加进某角色
//	 *
//	 * @param request
//	 * @param response
//	 * @return
//	 */
//	public ModelAndView checkPermission(HttpServletRequest request, HttpServletResponse response) {
//		String permisionIds = request.getParameter("permisionIds");
//		String roleId = request.getParameter("roleId");
//		String pType = request.getParameter("pType");
//		roleId = roleId == null ? "" : roleId.trim();
//		String[] permisionIdsArray = permisionIds.split(",");
//		List<Permission> permissions = new ArrayList<Permission>();
//		for (int i = 0; i < permisionIdsArray.length; i++) {
//			if (permisionIdsArray[i].equals("_ALL") && checkSRoleService.isHandleprivilege()) {
//				Permission permission = new Permission();
//				permission.setPermissionId("_ALL");
//				permission.setPermissionName("所有权限");
//				permissions.add(permission);
//				continue;
//			}
//			Permission permission = checkSRoleService.PermissionNotForRoleType(roleId, permisionIdsArray[i]);
//			if (permission != null) {
//				permissions.add(permission);
//			}
//		}
//		StringBuilder sb = new StringBuilder();
//		if (permissions.size() > 0) {
//			sb.append("{").append("\"info\":\"success !!\",").append("\"success\": true ,").append("\"permissionsInfo\":[");
//			for (int j = 0; j < permissions.size(); j++) {
//				if (j > 0) {
//					sb.append(",");
//				}
//				sb.append("{\n");
//				sb.append("\"permisionId\":\"").append(permissions.get(j).getPermissionId()).append("\"\n");
//				if (!(permissions.get(j).getPermissionId().equals("_ALL"))) {
//					sb.append(",\"pType\":\"").append(dic.getDictValue(pType, permissions.get(j).getpType())).append("\"\n");
//				}
//				sb.append(",\"permisionName\":\"").append(permissions.get(j).getPermissionName()).append("\"\n");
//				sb.append("}\n");
//			}
//			sb.append("]");
//			sb.append("}");
//		} else {
//			sb.append("{\"info\":'");
//			sb.append("没有不能加入的功能！");
//			sb.append("'");
//			sb.append(",");
//			sb.append("\"failure\":true,\"success\":false}");
//		}
//		outJson(sb, response);
//		return null;
//	}
//
//
    /**
     * 保存角色下的用户 1
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/srole/add-role-users")
	public UnifiedResponse<Void> saveRoleUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String loginIds = request.getParameter("loginIds");
		String loginNames = request.getParameter("loginNames");
		String partyIds = request.getParameter("partyIds");
		String[] arrayLoginId = loginIds.split(",");
		String[] arrayLoginName = loginNames.split(",");
		String[] arrayParty = partyIds.split(",");
		String roleId = request.getParameter("roleId");
		List<Integer> error = roleService.saveAllRoleUser(arrayLoginId, arrayLoginName, arrayParty, roleId);
		StringBuilder sbError = new StringBuilder();
		for (Integer in : error) {
			if (in != 0) {
				sbError.append(',');
			}
			sbError.append(arrayLoginName[in]);
		}
		if (error.size() == 0) {
			return UnifiedResponse.ok();
		} else {
			String description = "添加人员" + sbError + "失败,用户已存在于该角色";
			return UnifiedResponse.error("-1", description);
		}
	}
//

    /**
     * 删除角色下的用户 1
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/srole/del-role-user")
	public UnifiedResponse<Void> delRoleUser(HttpServletRequest request, HttpServletResponse response) {
		String roleId = request.getParameter("roleId");
		String roleUserIds = request.getParameter("roleUserIds");
		String loginIds = request.getParameter("loginIds");
		String partyIds = request.getParameter("partyIds");
		String types = request.getParameter("types");

		//String[] arrayRoleUserId = roleUserIds.substring(0, roleUserIds.lastIndexOf(",")).split(",");
        String[] arrayRoleUserId = roleUserIds.split(",");
		//String[] arrayLoginId = loginIds.substring(0, loginIds.lastIndexOf(",")).split(",");
        String[] arrayLoginId = loginIds.split(",");
		String[] arrayPartyId = partyIds.split(",");
		String[] arrayType = types.split(",");
		roleService.delSRoleUser(arrayRoleUserId, arrayLoginId, arrayPartyId, arrayType, roleId);
		SRole srole = roleService.findSRoleById(roleId);
		String roleName = "";
		if (srole != null) {
			roleName = srole.getRoleName();
		}
		String description = "权限角色" + roleName + "删除成员成功";
		return UnifiedResponse.ok();
	}
//
//	/**
//	 * **********************角色下查看系统功能***********start************************** ******
//	 */
//	// 显示
//	public ModelAndView viewRolePermission(HttpServletRequest request, HttpServletResponse response) {
//		String roleId = request.getParameter("roleId");
//
//		roleId = roleId == null ? "" : roleId.trim();
//		String roleName = "";
//		SRole role = roleService.findSRoleById(roleId);
//		Assert.notNull(role);
//		roleName = role.getRoleName();
//		request.setAttribute("roleId", roleId);
//		request.setAttribute("roleName", roleName);
//		return new ModelAndView("security/role/rolePermission");
//	}
//
	// 查询 1
    @PostMapping(value = "/srole/permissions")
	public UnifiedResponse<Page> rolePermissionPage(HttpServletRequest request, HttpServletResponse response) {
		int skipResults = 0;
		int pageSize = Page.DEFAULT_PAGE_SIZE;
		String start = request.getParameter("start");
		String limit = request.getParameter("pageSize");
		if (limit != null && !limit.trim().equals("")) {
			pageSize = Integer.parseInt(limit);
		}
		if (start != null && !start.trim().equals(""))
			skipResults = Integer.parseInt(start);
		String roleId = request.getParameter("roleId");
		roleId = roleId == null ? "" : roleId;
		String action = request.getParameter("action");
		action = action == null ? "view" : action.trim();
		String permissionId = request.getParameter("permissionId");
		String permissionName = request.getParameter("permissionName");
		permissionId = permissionId == null ? "" : permissionId.trim();
		permissionName = permissionName == null ? "" : permissionName.trim();

		String userlogin = SecurityUtil.getUser().getLoginId();

		Page page = roleSecurityService.queryRolePermission(userlogin, "sysModule", "SELECT", pageSize, skipResults, roleId, action, permissionId, permissionName);
		return UnifiedResponse.ok(page);
	}
//
//	// 打开添加页面
//	public ModelAndView addRolePermission(HttpServletRequest request, HttpServletResponse response) {
//		String roleId = request.getParameter("roleId");
//		roleId = roleId == null ? "" : roleId.trim();
//		String roleName = "";
//		SRole role = roleService.findSRoleById(roleId);
//		Assert.notNull(role);
//		roleName = role.getRoleName();
//		request.setAttribute("roleId", roleId);
//		request.setAttribute("roleName", roleName);
//		return new ModelAndView("security/role/addRolePermission");
//	}
//
//	/**
//	 * 保存角色功能
//	 *
//	 * @param request
//	 * @param response
//	 * @return
//	 */
//	public ModelAndView addRolePermissions(HttpServletRequest request, HttpServletResponse response) {
//		// 获得角色ID
//		String roleId = request.getParameter("roleId");
//		// 判断是否为空
//		if (UtilValidate.isEmpty(roleId)) {
//			// 为空
//			logger.info("没有获得角色Id，请检查");
//			throw new RuntimeException("没有获得角色ID");
//		} else {
//			// 不为空
//			logger.info("获得的角色ID为{}", roleId);
//			String permissions = request.getParameter("ids");// 获得提交上来的功能
//			// 检查是否提交上来的功能为空
//			if (UtilValidate.isEmpty(permissions)) {
//				logger.info("提交上来的功能列表为空");
//			} else {
//				// 分割提交功能为数组
//				String[] items = permissions.split(",");
//				logger.info("提交的功能列表为{}", permissions);
//				// 遍历保存
//				// RolePermission rolePermission = new RolePermission();
//				for (String item : items) {
//					RolePermission rolePermission = new RolePermission();
//					// 检查该角色是否已经有此功能
//					if (secSRoleService.getSecurity().rolePermissionExists(roleId, item)) {// 有此功能
//						logger.info("{}已经有功能{}", roleId, item);
//					} else {// 没有此功能
//						// 保存
//						rolePermission.setPermissionId(item);
//						rolePermission.setRoleId(roleId);
//						roleSecurityService.saveRolePermission(rolePermission);
//						logger.info("{}添加功能{}成功", roleId, item);
//					}
//				}
//			}
//		}
//		// 返回JSON字符串
//		outJson("{\"result\":\"保存成功\",\"success\":true}", response);
//		return null;
//	}
//

	/**
	 * 保存角色功能 1
	 * @param roleId
	 * @param rolePermissions
	 * @return
	 */
	@PostMapping(value = "/srole/save-role-permission/{roleId}")
	public UnifiedResponse<Void> addRolePermissionsWithType(@PathVariable(value = "roleId")String roleId,
															@RequestBody List<RolePermissionAddVO> rolePermissions) {

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < rolePermissions.size(); i++) {
			RolePermission rolePermission = new RolePermission();
			rolePermission.setPermissionId(rolePermissions.get(i).getPermissionId());
			rolePermission.setRoleId(roleId);
			rolePermission.setPermisionType(rolePermissions.get(i).getType());
			rolePermission.setPermisionTypeName(rolePermissions.get(i).getTypeName());
			rolePermission.setHasLower(rolePermissions.get(i).getHasLower());
			rolePermission.setPermisionLeafType(rolePermissions.get(i).getLeafType());
			rolePermission.setType(RolePermission.TYPE_ROLE);
			try {
				roleSecurityService.saveRolePermission(rolePermission);
				SRole srole = roleService.findSRoleById(roleId);
				String roleName = "";
				if (srole != null) {
					roleName = srole.getRoleName();
				}
			} catch (Exception e) {
				logger.info("{}", e.getMessage());
				logger.debug("", e);
				if (sb.length() == 0) {
					sb.append(',');
				}
				sb.append(rolePermission.getPermisionTypeName());
				SRole srole = roleService.findSRoleById(roleId);
				String roleName = "";
				if (srole != null) {
					roleName = srole.getRoleName();
				}
			}
		}
		if (sb.length() == 0) {
			return UnifiedResponse.ok();
		} else {
			return UnifiedResponse.error("-1","【" + sb + "】失败，其他成功");
		}
	}
//
//	// 保存角色功能
//	public ModelAndView saveRolePermission(HttpServletRequest request, HttpServletResponse response) {
//		String roleId = request.getParameter("roleId");
//		logger.info("角色ID为{}", roleId);
//		roleId = roleId == null ? "" : roleId.trim();
//		String permissionIds = request.getParameter("permissionIds");
//		permissionIds = permissionIds == null ? "" : permissionIds.trim();
//		String[] permissionId = permissionIds.split(",");
//		for (int i = 0; i < permissionId.length; i++) {
//			RolePermission rolePermission = new RolePermission();
//			rolePermission.setRoleId(roleId);
//			rolePermission.setPermissionId(permissionId[i]);
//			roleSecurityService.saveRolePermission(rolePermission);
//		}
//		return this.viewRolePermission(request, response);
//	}
//

	/**
	 * 删除角色下的功能 1
	 * @param ids
	 * @param permissionIds
	 * @return
	 */
	@DeleteMapping(value = "/srole/del-role-permission")
	public UnifiedResponse<Void> delRolePermission(@RequestParam(value = "ids") String ids,
										  @RequestParam(value = "permissionIds") String permissionIds) {
		String[] arrayId = ids.split(",");
		String[] arrayPermissionId = permissionIds.split(",");
		for (int i = 0; i < arrayId.length; i++) {
			roleSecurityService.removeRolePermission(arrayId[i], arrayPermissionId[i]);
		}
		return UnifiedResponse.ok();
	}
//
//	/**
//	 * **********************角色下查看系统功能**********end***************************** ******
//	 */
//	/**
//	 * **********************角色下查看数据对象**********start*************************** ********
//	 */
//	// 显示
//	public ModelAndView viewRoleDataObject(HttpServletRequest request, HttpServletResponse response) {
//		String roleId = request.getParameter("roleId");
//		roleId = roleId == null ? "" : roleId.trim();
//		String roleName = request.getParameter("roleName");
//		// 判断是否提交roleName参数，如果没有提交，则由角色Id找到相应的RoleName
//		if (UtilValidate.isEmpty(roleName)) {// 为空，如果roleId不空，由roleId查找相应的roleName
//			if (!roleId.equals("")) {
//				SRole srole = roleService.findSRoleById(roleId);
//				if (srole != null) {// 找到相应的权限角色
//					roleName = srole.getRoleName();
//				} else {// 没有找到相应的权限角色
//					logger.warn("There is not correspond roleName to {}", roleId);
//				}
//			} else {// roleId为空
//				roleName = "";
//			}
//		}
//		// roleName = roleName == null ? "" : roleName.trim();
//		request.setAttribute("roleId", roleId);
//
//		request.setAttribute("roleName", roleName);
//
//		// 查询所有的数据对象类型
//		String dataObjectTypeId = dataObjectTypeService.findSelectDoType();
//		request.setAttribute("dataObjectTypeId", dataObjectTypeId);
//		return new ModelAndView("security/role/roleDataObject");
//	}
//

	/**
	 * 分页查询 1 ()
	 * @param start
	 * @param pageSize
	 * @param roleId
	 * @param dataObjectId
	 * @param dataObjectName
	 * @param dataObjectTypeId
	 * @param dataObjectAction
	 * @return
	 */
	@PostMapping(value = "/srole/role-dataobjects")
	public UnifiedResponse<Page<Map<String, Object>>> roleDataObjectPage(@RequestParam(defaultValue = "0") Integer start,
																		 @RequestParam(defaultValue = Page.DEFAULT_PAGESIZE) Integer pageSize,
																		 @RequestParam String roleId,
																		 @RequestParam(required = false) String dataObjectId,
																		 @RequestParam(required = false) String dataObjectName,
																		 @RequestParam(required = false) String dataObjectTypeId,
																		 @RequestParam(required = false) String dataObjectAction) {
		RoleDataObject roleDataObject = new RoleDataObject();
		roleDataObject.setRoleId(roleId);
		roleDataObject.setDataObjectId(dataObjectId);
		roleDataObject.setDataObjectName(dataObjectName);
		roleDataObject.setDataObjectTypeId(dataObjectTypeId);
		roleDataObject.setDataObjectAction(dataObjectAction);
		Page<Map<String, Object>> page = roleSecurityService.queryRoleDataObject(pageSize, start, roleDataObject);
		return UnifiedResponse.ok(page);
	}
//
//	// 查询可添加的数据对象
//	public ModelAndView addRoleDataObjectPage(HttpServletRequest request, HttpServletResponse response) {
//		int skipResults = 0;
//		int pageSize = Page.DEFAULT_PAGE_SIZE;
//		String start = request.getParameter("start");
//		String limit = request.getParameter("limit");
//		if (limit != null && !limit.trim().equals("")) {
//			pageSize = Integer.parseInt(limit);
//		}
//		if (start != null && !start.trim().equals(""))
//			skipResults = Integer.parseInt(start);
//		String roleId = request.getParameter("roleId");
//		roleId = roleId == null ? "" : roleId.trim();
//		Page<Map<String, Object>> page = roleSecurityService.queryDataObjectRole(pageSize, skipResults, roleId);
//		PageUtil<Map<String, Object>> out = new PageUtil<Map<String, Object>>(page);
//		super.outJson(out, response);
//		return null;
//	}
//
//	/**
//	 * 返回数据对象功能树的JSON数据(gyz added at 2008-3-29)
//	 *
//	 * @param request
//	 * @param response
//	 * @return
//	 */
//	public ModelAndView addRoleDataObjectData(HttpServletRequest request, HttpServletResponse response) {
//		StringBuilder builder = new StringBuilder();// Json字符串Builder
//		// 获取展示节点
//		String parent = request.getParameter("parentId");
//		logger.info("当前节点VALUE:{}", parent);
//		List<Object> list = new ArrayList<Object>();// 需要输出JSON的对象列表
//		String parameter = request.getParameter("type");// 节点类型参数(type是数据对象类型、
//		// object是数据对象)
//		logger.info("当前节点TYPE：{}", parameter);
//		// 判断是否为空
//		if (UtilValidate.isEmpty(parent)) {// 为空,表明是根节点
//			list.addAll(roleSecurityService.queryDataObjectType(null));
//		} else {// 获取该节点下的所有数据类型及数据对象
//
//			if (parameter.equalsIgnoreCase("type")) {// 如果是数据对象类型
//				// 加载所有的直接子数据对象类型
//				list.addAll(roleSecurityService.queryDataObjectType(parent));
//				// 加载所有的直接子数据对象
//				list.addAll(roleSecurityService.queryDataObject(parent));
//				// 对数据对象类型所有数据对象的功能数据选择
//				list.addAll(dic.getDictList("securityAction"));
//			} else if (parameter.equalsIgnoreCase("object")) {// 如果是数据对象
//				// 加载所有的对于数据对象的功能
//				List<DictionaryData> data = dic.getDictList("securityAction");// 从字典中取出功能数据
//				// （
//				// 添加
//				// 、
//				// 删除
//				// 、
//				// 修改等
//				// ）
//				list.addAll(data);
//			}
//
//		}
//		// 输出JSON
//		builder.append("[");
//		if (UtilValidate.isEmpty(parameter) || parameter.equalsIgnoreCase("type")) {// 如果是数据对象类型
//			for (Object item : list) {
//				builder.append("{");
//				// 判断ITEM类型
//				Map<String, String> map = new HashMap<String, String>();
//				if (item instanceof DataObjectType) {//
//					map.put("value", ((DataObjectType) item).getDataObjectTypeId());
//					map.put("type", "type");
//					map.put("text", ((DataObjectType) item).getDataObjectTypeName());
//					map.put("leaf", "false");
//				} else if (item instanceof DataObject) {
//					map.put("value", ((DataObject) item).getDataObjectId());
//					map.put("type", "object");
//					map.put("text", ((DataObject) item).getDataObjectName());
//					map.put("leaf", "false");
//				} else if (item instanceof DictionaryData) {
//					map.put("value", ((DictionaryData) item).getCode());
//					map.put("type", "leaf");
//					map.put("text", ((DictionaryData) item).getDictdataValue());
//					map.put("leaf", "true");
//				}
//				// 根据类型不同，输出不同的数据
//				builder.append("id:'");
//				builder.append(parent).append("|").append(map.get("value")).append("|").append("type");
//				builder.append("',");
//				builder.append("value:'").append(map.get("value")).append("',");
//				builder.append("text:'").append(map.get("text")).append("',");
//				builder.append("leaf:").append(map.get("leaf")).append(",");
//				if (map.get("leaf").equalsIgnoreCase("true")) {// 叶子节点
//					builder.append("checked:false,");
//				}
//				builder.append("params:{type:'").append(map.get("type")).append("'}");
//				builder.append("},");
//			}
//		} else if (parameter.equalsIgnoreCase("object")) {// 如果是数据对象
//			for (Object item : list) {
//				builder.append("{");
//				builder.append("id:'").append(parent).append("|").append(((DictionaryData) item).getCode()).append("|").append("object',");
//				builder.append("value:'").append(((DictionaryData) item).getCode()).append("',");
//				builder.append("text:'").append(((DictionaryData) item).getDictdataValue()).append("',");
//				builder.append("leaf:true,");
//				builder.append("params:{type:'leaf'},");
//				builder.append("checked:false},");
//			}
//
//		}
//		// 如果有逗号，去掉最后一个逗号
//		if (builder.indexOf(",") != -1) {
//			builder.deleteCharAt(builder.lastIndexOf(","));
//		}
//		builder.append("]");
//		logger.debug(builder.toString());
//		outJson(builder.toString(), response);
//		return null;
//	}
//
//	public ModelAndView updateDataObjectSelect(HttpServletRequest request, HttpServletResponse response) {
//		List<DataObjectType> list = roleSecurityService.findAllRoleDataObject(dateObjectType);
//		request.setAttribute("list", list);
//
//		return new ModelAndView("security/dataObject/dataObjectSearch");
//	}
//
//	public ModelAndView updateDataObjectSelectLayer(HttpServletRequest request, HttpServletResponse response) {
//		List<DataObjectType> list = roleSecurityService.findAllRoleDataObject(dateObjectType);
//		request.setAttribute("list", list);
//
//		return new ModelAndView("security/dataObject/dataObjectSearchLayer");
//	}
//
//	public ModelAndView dataObjectSelect(HttpServletRequest request, HttpServletResponse response) {
//		// List<DataObjectType> list = roleSecurityService.queryDataObjectType(null);
//
//		List<Permission> listPermission = this.permissionTypeService.findAllChildPermision(this.secretTypeId, super.getCuruserLoginId(request));
//		List<String> listStr = new ArrayList<String>();
//		for (Permission permission : listPermission) {
//
//			if (super.getSecurity().hasPermission(super.getCuruserLoginId(request), permission.getPermissionId()))
//				listStr.add(permission.getPermissionId());
//
//		}
//		List<DataObjectType> list = roleSecurityService.queryDataObjectType(null, listStr);
//		request.setAttribute("list", list);
//
//		return new ModelAndView("security/dataObject/dataObjectSelect");
//	}
//
//	public ModelAndView dataObjectSelectLayer(HttpServletRequest request, HttpServletResponse response) {
//		// List<DataObjectType> list = roleSecurityService.queryDataObjectType(null);
//
//		List<Permission> listPermission = this.permissionTypeService.findAllChildPermision(this.secretTypeId, super.getCuruserLoginId(request));
//		List<String> listStr = new ArrayList<String>();
//		for (Permission permission : listPermission) {
//
//			if (super.getSecurity().hasPermission(super.getCuruserLoginId(request), permission.getPermissionId()))
//				listStr.add(permission.getPermissionId());
//
//		}
//		List<DataObjectType> list = roleSecurityService.queryDataObjectType(null, listStr);
//		String id = "";
//		String name = "";
//		for (DataObjectType dataObjectType : list) {
//			id += dataObjectType.getDataObjectTypeId() + ",";
//			name += dataObjectType.getDataObjectTypeName() + ",";
//		}
//		request.setAttribute("id", id);
//		request.setAttribute("name", name);
//		return new ModelAndView("security/dataObject/dataObjectSelectLayer");
//	}
//
//	public ModelAndView openLiebiao(HttpServletRequest request, HttpServletResponse response) {
//		String id = request.getParameter("id");
//		String name = request.getParameter("name");
//		String showshujuduixiang = request.getParameter("showshujuduixiang");
//		if(UtilValidate.isNotEmpty(showshujuduixiang)){
//			List<DataObjectType> list = roleSecurityService.findAllRoleDataObject(dateObjectType);
//			request.setAttribute("list", list);
//			request.setAttribute("showshujuduixiang", showshujuduixiang);
//		}
//		request.setAttribute("id", id);
//		request.setAttribute("name", name);
//		return new ModelAndView("security/dataObject/liebiao");
//	}
//
//
	/**
	 * 获取数据对象树 1
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/srole/dataobject-tree",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public UnifiedResponse<List<Map<String, Object>>> dataObjectTree(HttpServletRequest request) {
		String parent = request.getParameter("parentId");
		String type = request.getParameter("type");
		if (UtilValidate.isEmpty(parent)) {
			parent = "root";
		}
		List<Map<String, Object>> json = new ArrayList<>();
		if ("root".equals(parent)) {
			List<Permission> listPermission = this.permissionTypeService.findAllChildPermision("DataObjectTypeSecret-Manager", SecurityUtil.getUser().getLoginId());
			List<String> listStr = new ArrayList<>();
			for (Permission permission : listPermission) {
				if (iSecurity.hasPermission(SecurityUtil.getUser().getLoginId(), permission.getPermissionId()))
					listStr.add(permission.getPermissionId());
			}
			List<DataObjectType> list = roleSecurityService.queryDataObjectType(null, listStr);
			prossessDataObjectTypeList(list, json);
		} else if ("type".equals(type)) {
			List<DataObjectType> list = roleSecurityService.queryDataObjectType(parent);
			prossessDataObjectTypeList(list, json);
			// List<DataObject> doList = roleSecurityService.queryDataObject(parent, parent);
			List<DataObject> doList = roleSecurityService.queryDataObject(SecurityUtil.getUser().getLoginId(), "systemDataObjectType", "SELECT", parent, parent);
			prossessDataObjectList(doList, json);
		} else if ("object".equals(type)) {
			// 0 为objectid, 1为objecttypeid
			String[] ids = parent.split(",");
			// addAction(ids[1],json);
			List<DataObject> doList = roleSecurityService.queryDataObject(SecurityUtil.getUser().getLoginId(), "systemDataObjectType", "SELECT", ids[1], ids[0]);
			// List<DataObject> doList = roleSecurityService.queryDataObject(ids[1], ids[0]);
			prossessDataObjectList(doList, json);
		}
		return UnifiedResponse.ok(json);
	}
//
//	public ModelAndView updateDataObjectTree(HttpServletRequest request, HttpServletResponse response) {
//		String parent = request.getParameter("parentId");
//		String type = request.getParameter("type");
//		if (UtilValidate.isEmpty(parent)) {
//			parent = "root";
//		}
//		List<Map<String, Object>> json = new ArrayList<Map<String, Object>>();
//		if ("root".equals(parent)) {
//			List<DataObjectType> list = roleSecurityService.findAllRoleDataObject(dateObjectType);
//			prossessDataObjectTypeList(list, json);
//		} else if ("type".equals(type)) {
//			// addAction(parent,json);
//
//			List<DataObjectType> list = roleSecurityService.queryDataObjectType(parent);
//			prossessDataObjectTypeList(list, json);
//
//			List<DataObject> doList = roleSecurityService.queryDataObject(parent, parent);
//
//			prossessDataObjectList(doList, json);
//		} else if ("object".equals(type)) {
//			// 0 为objectid, 1为objecttypeid
//			String[] ids = parent.split(";");
//			// addAction(ids[1],json);
//			List<DataObject> doList = roleSecurityService.queryDataObject(ids[1], ids[0]);
//			prossessDataObjectList(doList, json);
//		}
//
//		outJson(List2Json(json), response);
//		return null;
//	}
//
	private void prossessDataObjectList(List<DataObject> list, List<Map<String, Object>> json) {

		for (DataObject dataObject : list) {
			Map<String, Object> map = new HashMap<>();
			String id = java.util.UUID.randomUUID().toString();
			map.put("id", id);
			map.put("value", dataObject.getDataObjectId() + ',' + dataObject.getDataObjectTypeId());
			map.put("name", dataObject.getDataObjectName());
			map.put("isParent", roleSecurityService.queryDataObject(dataObject.getDataObjectTypeId(), dataObject.getDataObjectId()).size() != 0);
			map.put("type", "object");
			map.put("checked", false);
			map.put("uiProvider", "col");
			List<String> temp = new ArrayList<>(1);
			temp.add("LOWALL");
			map.put("checkActions",temp);
			map.put("action", getActJson(getAction(dataObject.getDataObjectTypeId()), dataObject.getDataObjectTypeId(), id));
			json.add(map);
		}
	}
//
	private void prossessDataObjectTypeList(List<DataObjectType> list, List<Map<String, Object>> json) {
		for (DataObjectType dataObjectType : list) {
			List<Map<String, String>> actlist = getAction(dataObjectType.getDataObjectTypeId());
			Map<String, Object> map = new HashMap<>();
			String id = java.util.UUID.randomUUID().toString();
			map.put("id", id);
			map.put("value", dataObjectType.getDataObjectTypeId());
			map.put("name", dataObjectType.getDataObjectTypeName());
			map.put("isParent", true);
			map.put("type", "type");
			map.put("uiProvider", "col");
			List<String> temp = new ArrayList<>(1);
			temp.add("LOWALL");
			map.put("checkActions",temp);
			map.put("action", getActJson(actlist, dataObjectType.getDataObjectTypeId(), id));
			json.add(map);
		}
	}
//
	private List<Map<String, Object>> getActJson(List<Map<String, String>> list, String dataObjectTypeId, String nodeId) {
		List<Map<String, Object>> templist = new ArrayList<>();
		for (Map<String, String> map : list) {
			Map<String, Object> tempMap = new HashMap<>();
			tempMap.putAll(map);
			tempMap.put("nodeId", nodeId);
			tempMap.put("dataObjectTypeId", dataObjectTypeId);
			templist.add(tempMap);
		}
		return templist;
	}
//
	private List<Map<String, String>> getAction(String type) {
		DataObjectType dataObjectType = dataObjectTypeService.findByTypeId(type);
		List<IDictionaryData> diclist = null;

		if (UtilValidate.isNotEmpty(dataObjectType.getActionDic())) {
			diclist = dic.getDictList(dataObjectType.getActionDic());
		} else {
			diclist = dic.getDictList("securityAction");
		}
		List<Map<String, String>> list = new ArrayList<>();
//		Map<String, String> keymap = new HashMap<>();
//		keymap.put("key", RoleDataObject.LOWALL);
//		keymap.put("value", "所有");
//		keymap.put("title", "管理员权限，本级及以下所有权限");
//		list.add(keymap);
		for (IDictionaryData dictionaryData : diclist) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("key", dictionaryData.getCode());
			map.put("value", dictionaryData.getDictdataValue());
			if (RoleDataObject.LOWALL.equalsIgnoreCase(dictionaryData.getCode())) {
				map.put("title", "管理员权限，本级及以下所有权限");
			}
			list.add(map);
		}
		return list;
	}
//
//
//	private String List2Json(List<Map<String, Object>> list) {
//		if (UtilValidate.isEmpty(list)) {
//			return "[]";
//		}
//		StringBuilder json = new StringBuilder();
//
//		for (Map<String, Object> map : list) {
//			if (json.length() != 0) {
//				json.append(',');
//			}
//			StringBuilder object = new StringBuilder();
//			for (String key : map.keySet()) {
//				if (object.length() != 0) {
//					object.append(',');
//				}
//				object.append(key).append(':');
//				Object value = map.get(key);
//				if (value instanceof List) {
//					object.append(List2Json((List<Map<String, Object>>) value));
//				} else if (value instanceof String) {
//					object.append('\'').append(value).append('\'');
//				} else {
//					object.append(value);
//				}
//			}
//			object = new StringBuilder().append('{').append(object).append('}');
//			json.append(object);
//		}
//
//		json = new StringBuilder().append('[').append(json).append(']');
//		logger.info("json:{}", json);
//		return json.toString();
//	}
//
//	public ModelAndView dataObjectQuery(HttpServletRequest request, HttpServletResponse response) {
//		String startstr = request.getParameter("start");
//		String pageSizestr = request.getParameter("pageSize");
//		int start = 0;
//		int pageSize = Page.DEFAULT_PAGE_SIZE;
//
//		// 从属关系查询返回所有记录
//		if (UtilValidate.isNotEmpty(startstr))
//			start = Integer.parseInt(startstr);
//		if (UtilValidate.isNotEmpty(pageSizestr))
//			pageSize = Integer.parseInt(pageSizestr);
//		String typeId = request.getParameter("typeId");
//		String dataobjectname = request.getParameter("dataobjectname");
//		Map<String, Object> param = UtilHttp.filterBlank(request.getParameterMap());
//		param.put("dataobjectname", "%" + dataobjectname + "%");
//		Page<DataObject> page = roleSecurityService.queryDataObject(typeId, param, start, pageSize);
//		List<DataObject> list = page.getResult();
//		List<Map<String, Object>> pageList = UtilMisc.toListMap(list, null);
//		for (Map<String, Object> map : pageList) {
//			map.put("action", List2Json(getActJson(getAction(typeId), typeId, (String) map.get("id"))));
//		}
//		Page<Map<String, Object>> mappage = new Page<Map<String, Object>>(start, page.getTotalCount(), pageSize, pageList);
//		PageUtil out = new PageUtil(mappage);
//		super.outJson(out, response);
//		return null;
//	}
//
	// 保存角色数据对象
	public ModelAndView saveRoleDataObject(HttpServletRequest request, HttpServletResponse response) {
		String roleId = request.getParameter("roleId");
		roleId = roleId == null ? "" : roleId.trim();
		String dataObjectIds = request.getParameter("dataObjectId");
		dataObjectIds = dataObjectIds == null ? "" : dataObjectIds.trim();
		String actions = request.getParameter("action");
		actions = actions == null ? "" : actions.trim();
		String dataObjectTypeIds = request.getParameter("dotypeid");
		dataObjectTypeIds = dataObjectTypeIds == null ? "" : dataObjectTypeIds.trim();
		String dotypeactions = request.getParameter("dotypeaction");
		dotypeactions = dotypeactions == null ? "" : dotypeactions.trim();
		String[] arrayDataObject = dataObjectIds.split(",");
		String[] arrayDataObjectTypeAction = dotypeactions.split(",");
		String[] arrayDataObjectTypeId = dataObjectTypeIds.split(",");
		for (int i = 0; i < arrayDataObject.length; i++) {
			RoleDataObject roleDataObject = new RoleDataObject();
			roleDataObject.setRoleId(roleId);
			roleDataObject.setDataObjectId(arrayDataObject[i]);
			roleDataObject.setDataObjectAction(arrayDataObjectTypeAction[i]);
			roleDataObject.setDataObjectTypeId(arrayDataObjectTypeId[i]);
			if (!roleSecurityService.ValData(roleId, arrayDataObject[i], arrayDataObjectTypeAction[i])) {
				roleSecurityService.saveRoleDataObject(roleDataObject);
			}
		}
		return null;
	}
//
//	/**
//	 * 保存当前角色的功能（在原有功能上增加）(gyz added at 2008-3-30)
//	 *
//	 * @param request
//	 * @param response
//	 * @return
//	 */
//	public ModelAndView saveAllRoleDataObject(HttpServletRequest request, HttpServletResponse response) {
//		String roleId = request.getParameter("roleId");// 获得当前角色ID
//		if (UtilValidate.isEmpty(roleId)) {
//			SetErrMsg(request, "没有获得当前角色");
//			return null;
//		}
//		String dataObjectIds = request.getParameter("dataObject");// 数据对象及操作
//		String dataObjectType = request.getParameter("dataObjectType");// 数据对象类型
//		// 分解提交上来的参数
//		String[] dataObject = dataObjectIds.split(",");// dataObject中元素格式为:parent
//		// |value|type
//		String[] objectType = dataObjectType.split(",");
//		for (int i = 0; i < dataObject.length; i++) {// 遍历提交上来的数据对象功能
//			RoleDataObject roleDataObject = new RoleDataObject();// 临时对象
//			// 分解元素
//			String[] items = dataObject[i].split("\\|");// 转义，避免当作正则表达式中的|
//			String tempDataObjectId = "";
//			if (items.length >= 3) {// 判断规范性
//				roleDataObject.setRoleId(roleId);
//				if (items[2].equals("type")) {// 对于数据对象类型ALL的操作
//					tempDataObjectId = objectType[i].concat("ALL");
//					roleDataObject.setDataObjectId(objectType[i].concat("ALL"));
//				} else {// 数据对象的操作
//					tempDataObjectId = items[0];
//					roleDataObject.setDataObjectId(items[0]);
//				}
//				roleDataObject.setDataObjectAction(items[1]);
//				roleDataObject.setDataObjectTypeId(objectType[i]);
//				// 判断是否已存在该数据对象功能，如果不存在，持久化到数据库中
//				if (!roleSecurityService.ValData(roleId, tempDataObjectId, items[1])) {
//					roleSecurityService.saveRoleDataObject(roleDataObject);
//				}
//			}
//
//		}
//		// 返回JSON数据
//		setReturnMsg(request, "{\"result\":\"保存成功\",\"success\":true}");
//		return null;
//	}
//

//    /**
//     * 保存角色数据对象
//     * @param request
//     * @param response
//     * @return
//     */
//	public ModelAndView saveDataObject(HttpServletRequest request, HttpServletResponse response) {
//		String roleId = request.getParameter("roleId");// 获得当前角色ID
//		if (UtilValidate.isEmpty(roleId)) {
//			return null;
//		}
//		String dataObjectIds = request.getParameter("dataObject");
//		String actions = request.getParameter("action");
//		String types = request.getParameter("type");
//		String names = request.getParameter("name");
//
//		String[] dataObjectId = dataObjectIds.split(",");
//		String[] action = actions.split(",");
//		String[] type = types.split(",");
//		String[] name = names.split(",");
//
//		for (int i = 0; i < dataObjectId.length; i++) {
//			if (!roleSecurityService.ValData(roleId, dataObjectId[i], action[i], type[i])) {
//				RoleDataObject roleDataObject = new RoleDataObject();// 临时对象
//				roleDataObject.setRoleId(roleId);
//				roleDataObject.setDataObjectId(dataObjectId[i]);
//				roleDataObject.setDataObjectAction(action[i]);
//				roleDataObject.setDataObjectTypeId(type[i]);
//				roleDataObject.setDataObjectName(name[i]);
//				roleSecurityService.saveRoleDataObject(roleDataObject);
//				SRole srole = roleService.findSRoleById(roleId);
//				String roleName = "";
//				if (srole != null) {
//					roleName = srole.getRoleName();
//				}
//				String description = "权限角色" + roleName + "添加数据对象" + name[i] + action[i] + "成功";
//			}
//		}
//		return null;
//	}

	/**
	 * 保存角色数据对象 1
	 * @param roleDataObjectAddVOS
	 * @param roleId
	 * @return
	 */
	@PostMapping(value = "/srole/save-dataobejcts/{roleId}",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public UnifiedResponse<Void> saveDataObject(@RequestBody @Validated List<RoleDataObjectAddVO> roleDataObjectAddVOS,
												@PathVariable @NotBlank(message = "角色ID不能为空!") String roleId){
		for (RoleDataObjectAddVO vo : roleDataObjectAddVOS) {
			List<String> actions = vo.getActions();
			String dataObjectId = vo.getDataObjectId();
			String dataObjectName = vo.getDataObjectName();
			String dataObjectTypeId = vo.getDataObjectTypeId();
			actions.stream().forEach(action -> {
				if (!roleSecurityService.ValData(roleId,dataObjectId,action,dataObjectTypeId)) {
					RoleDataObject roleDataObject = new RoleDataObject();
					roleDataObject.setRoleId(roleId);
					roleDataObject.setDataObjectId(dataObjectId);
					roleDataObject.setDataObjectAction(action);
					roleDataObject.setDataObjectName(dataObjectName);
					roleDataObject.setDataObjectTypeId(dataObjectTypeId);
					roleSecurityService.saveRoleDataObject(roleDataObject);
				}
			});
		}
		return UnifiedResponse.ok();
	}

    /**
     * 删除角色下的数据对象 1
     * @return
     */
    @DeleteMapping(value = "/srole/delete-role-dataobject")
	public UnifiedResponse<Void> delRoleDataObject(@RequestParam(value = "id") @NotBlank(message = "id不能为空!") String id,@RequestParam(value = "doTypeId") @NotBlank(message = "数据对象类型ID不能为空!") String doTypeId) {
    	roleSecurityService.removeRoleDataObject(id, doTypeId);
		return UnifiedResponse.ok();
	}
//
//	/**
//	 * *********************角色下查看数据对象**********end****************************** *****
//	 */
//	/**
//	 * *********************角色下组织和用户组**********start**************************** *******
//	 */
//	public UnifiedResponse<String> saveRoleOrgan(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		String loginNames = request.getParameter("loginNames");
//		loginNames = loginNames == null ? "" : loginNames.trim();
//		String partyIds = request.getParameter("partyIds");
//		partyIds = partyIds == null ? "" : partyIds.trim();
//		String[] arrayLoginName = loginNames.split(",");
//		String[] arrayPartyId = partyIds.split(",");
//		String roleId = request.getParameter("roleId");
//		roleId = roleId == null ? "" : roleId.trim();
//		String roleName = request.getParameter("roleName");
//		roleName = roleName == null ? "" : roleName.trim();
//		// 0为组织、1为用户组
//		String type = request.getParameter("type");
//		type = type == null || type.equals("0") ? SRoleUser.typeOrgan : SRoleUser.typeUserGroup;
//		List<Integer> error = roleService.saveOrganAndUserGroup(type, arrayPartyId, arrayLoginName, roleId);
//		StringBuilder sbError = new StringBuilder();
//		for (Integer in : error) {
//			if (in != 0) {
//				sbError.append(',');
//			}
//			sbError.append(arrayLoginName[in]);
//		}
//		if (error.size() == 0) {
//			return UnifiedResponse.ok("保存成功");
//		} else {
//			String description = "权限角色" + roleName + "添加组织" + sbError + "失败";
//			logger.error(description);
//			return UnifiedResponse.ok("当前角色已存在：" + sbError);
//		}
//	}
//
//	/*
//	 * 提供给人员的权限角色
//	 */
//	public ModelAndView sRoleInfo(HttpServletRequest request, HttpServletResponse response) {
//		String dataId = request.getParameter("dataid");
//		String userLogin = SecurityUtil.getUser().getLoginId();
//		try {
//			if (UtilValidate.isNotEmpty(dataId)) {
//				//dataId = InfoEngine.getInfoEngine().decode(dataId);
//				request.setAttribute("dataid", dataId);
//				List<SRole> list = secSRoleService.getSRolesByPartyId(userLogin, "sysModule", "SELECT", dataId);
//				request.setAttribute("sroleinfo", list);
//			}
//		} catch (Exception e) {
//			logger.error("null point", e);
//		}
//		return new ModelAndView("security/role/sroleInfo");
//	}
//
//	/**
//	 * *********************角色下组织**********end********************************** ***
//	 */
//
//	/**
//	 * 根据用户登录Id显示该登录用户所具的所有角色
//	 *
//	 * @param request
//	 * @param response
//	 * @return
//	 */
//	public UnifiedResponse<Page<SRole>> queryRole(HttpServletRequest request, HttpServletResponse response) {
//		String loginId = request.getParameter("loginId");
//		String roleName = request.getParameter("roleName");
//		String businessId = request.getParameter("businessId");
//		String start = request.getParameter("start");
//		int skipResults = 0;
//		if (start != null && !start.trim().equals(""))
//			skipResults = Integer.parseInt(start);
//		Page<SRole> result = new Page<SRole>();
//		if (UtilValidate.isNotEmpty(loginId)) {
//			Map<String, Object> conds = new HashMap<String, Object>();
//			if (UtilValidate.isNotEmpty(roleName)) {
//				conds.put("roleName", roleName);
//				String module = request.getParameter("module");
//				if (UtilValidate.isNotEmpty(module)) {
//					if (module.startsWith("%")) {
//						module = module.substring(1);
//					}
//					if (module.endsWith("%")) {
//						module = module.substring(0, module.length() - 1);
//					}
//				}
//			}
//			if (UtilValidate.isNotEmpty(businessId)) {
//				conds.put("businessId", businessId);
//			}
//			result = secSRoleService.getSRolesByLoginId(loginId, conds, skipResults);
//			UserLogin userLogin = userLoginServiceProxy.findById(loginId);
//			Person person = null;
//			String name = "";
//			if (userLogin != null) {
//				person = personServiceProxy.findPersonById(userLogin.getPartyId());
//			}
//			if (person != null) {
//				name = person.getFullName();
//			}
//		}
//		return UnifiedResponse.ok(result);
//	}
//
//	/**
//	 * 根据登录用户的Id查找该用户所具的功能页面
//	 *
//	 * @return
//	 */
//	public ModelAndView permByLogIdPage(HttpServletRequest request, HttpServletResponse response) {
//		return new ModelAndView("security/role/queryPerm");
//	}
//
//	/**
//	 * 根据登录用户的Id查找该用户所具的功能
//	 *
//	 * @param request
//	 * @param response
//	 * @return
//	 */
//	public UnifiedResponse<Page<Permission>> queryPermByLogin(HttpServletRequest request, HttpServletResponse response) {
//		String loginId = request.getParameter("loginId");
//		String permissionId = request.getParameter("permissionID");
//		String permissionName = request.getParameter("permissionName");
//		String start = request.getParameter("start");
//		int skipResults = 0;
//		if (start != null && !start.trim().equals(""))
//			skipResults = Integer.parseInt(start);
//		Page<Permission> result = new Page<Permission>();
//		if (UtilValidate.isNotEmpty(loginId)) {
//			Map<String, Object> conds = new HashMap<String, Object>();
//			if (UtilValidate.isNotEmpty(permissionId))
//				conds.put("permissionID", permissionId);
//			if (UtilValidate.isNotEmpty(permissionName))
//				conds.put("permissionName", permissionName);
//			result = permissionService.queryPermByLoginId(loginId, conds, skipResults);
//			UserLogin userLogin = userLoginServiceProxy.findById(loginId);
//			Person person = null;
//			String name = "";
//			if (userLogin != null) {
//				person = personServiceProxy.findPersonById(userLogin.getPartyId());
//			}
//			if (person != null) {
//				name = person.getFullName();
//			}
//		}
//		return UnifiedResponse.ok(result);
//	}
//
//
//	/**
//	 * 权限角色的层次树
//	 *
//	 * @param request
//	 * @param response
//	 * @return
//	 */
//	public ModelAndView sroleTree(HttpServletRequest request, HttpServletResponse response) {
//		String parentId = request.getParameter("parentId");
//		StringBuilder sb = new StringBuilder();
//		List<SRole> sons;
//		if (UtilValidate.isEmpty(parentId) || "root".equalsIgnoreCase(parentId)) {
//			sons = roleService.getSonRoles(null, SecurityUtil.getUser().getLoginId());
//		} else {
//			sons = roleService.getSonRoles(parentId, SecurityUtil.getUser().getLoginId());
//		}
//		sb.append("[");
//		if (UtilValidate.isNotEmpty(sons)) {
//			for (SRole srole : sons) {
//				sb.append("{");
//				sb.append("'id':'").append(srole.getRoleId()).append("'");
//				sb.append(",");
//				sb.append("'value':'").append(srole.getRoleId()).append("'");
//				sb.append(",");
//				sb.append("'text':'").append(srole.getRoleName()).append("'");
//				sb.append(",");
//				sb.append("'checked':false");
//				List<SRole> childs = roleService.getSonRoles(srole.getRoleId(), SecurityUtil.getUser().getLoginId());
//				sb.append(",");
//				if (childs.size() != 0) {
//					sb.append("'leaf':false");
//				} else {
//					sb.append("'leaf':true");
//				}
//				sb.append("}");
//				sb.append(",");
//			}
//		}
//		int lastIndex = sb.lastIndexOf(",");
//		if (lastIndex != -1) {
//			sb.deleteCharAt(lastIndex);
//		}
//		sb.append("]");
//		logger.debug("the srole tree is {}", sb);
//		outJson(sb.toString(), response);
//		return null;
//	}

}
